<script setup lang="ts">
import CpNavbar from '@/components/cp-navbar.vue'
import RoomStatus from './components/room-status.vue'
import RoomAction from './components/room-action.vue'
import RoomMessage from './components/room-message.vue'

import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType } from '@/enums'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { OrderType } from '@/enums'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const list = ref<Message[]>([])

let socket: Socket
//控制默认消息记录滚动到最底部
const initFirst = ref(true)
const userStore = useUserStore()
const route = useRoute()
// 组件挂载时建立链接
onMounted(async () => {
  socket = io(baseURL, {
    // 登录权限认证
    auth: {
      token: `Bearer ${userStore.user?.token}`
    },
    // 订单id
    query: {
      orderId: route.query.orderId
    }
  })
  socket.on('connect', () => {
    console.log('链接成功')
    // 如果断开连接后再次连接，需要清空聊天记录
    list.value = []
  })
  socket.on('disconnect', () => {
    console.log('链接断开')
  })
  socket.on('error', (error) => {
    console.log('错误异常', error)
  })

  // 获取默认的聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // console.log(data)

    // 转换为通用消息
    const arr: Message[] = []

    data.forEach((item, index) => {
      // 记录每段消息的开始时间，作为下一次请求的开始时间
      if (index === 0) time.value = item.createTime

      // 自己创建一则通用消息
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })

      item.items.forEach((item) => arr.push({ ...item, notScorll: initFirst.value === false }))
    })
    // 追加到聊天消息列表
    list.value.unshift(...arr)

    // 消息加载完成后关闭loading状态
    loading.value = false

    // 在接收聊天记录后需判断是否还有聊天数据，没有的话则提示用户
    if (!data.length) return showToast('没有更多聊天记录了')

    // 第一次获取消息需要滚动到最底部
    nextTick(() => {
      if (initFirst.value) {
        // 默认加载的消息，需要用最后一条消息设置已读，之前所有消息即是已读
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
        initFirst.value = false
      }
    })
  })

  // 获取订单状态
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })

  // 获取文字消息
  socket.on('receiveChatMsg', (res: Message) => {
    list.value.push(res)

    // 接收到消息的时候，需要把消息设置为已读
    socket.emit('updateMsgStatus', res.id)
    // 滚动到最底部
    nextTick(() => {
      window.scrollTo(0, document.body.scrollHeight)
    })
  })
})

// 组件销毁时断开链接
onUnmounted(() => {
  socket.close()
})

// 获取接诊状态信息
const consult = ref<ConsultOrderItem>()
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
})

// 发送消息给服务器
const sentText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: userStore.user?.id, //发送人
    to: consult.value?.docInfo?.id, //接收人
    msgType: 1, //消息类型 1：文字消息
    msg: {
      content: text
    }
  })
}

// 发送图片给服务器
const sentImg = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: userStore.user?.id, //发送人
    to: consult.value?.docInfo?.id, //接收人
    msgType: 4,
    msg: {
      picture: img
    }
  })
}

// 下拉刷新获取更多的聊天记录
const loading = ref(false)
// 记录每段消息的开始时间，作为下一次请求的开始时间
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page">
    <!-- tabbar -->
    <CpNavbar title="问诊室" />
    <!-- 顶部订单状态 -->
    <RoomStatus :status="consult?.status" :countdown="consult?.countdown" />
    <!-- 消息卡片 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage :list="list" />
    </van-pull-refresh>
    <!-- 底部操作栏 -->
    <RoomAction
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sentText"
      @send-img="sentImg"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
